package com.example.smartcitymovie.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.bumptech.glide.Glide;
import com.example.smartcitymovie.MyApplication;
import com.example.smartcitymovie.R;
import com.example.smartcitymovie.adapter.RecycleViewAdapter;
import com.example.smartcitymovie.bean.AreaThreaterBean;
import com.example.smartcitymovie.bean.FunctionListBean;
import com.example.smartcitymovie.bean.LocalAddressBean;
import com.example.smartcitymovie.bean.MovieBannerBean;
import com.example.smartcitymovie.bean.MovieListBean;
import com.example.smartcitymovie.bean.PreviewMovieListBean;
import com.example.smartcitymovie.bean.TodayWeatherBean;
import com.example.smartcitymovie.dataRepo.ApiData;
import com.example.smartcitymovie.databinding.FragmentHomeBinding;
import com.example.smartcitymovie.ui.movie.ChooseTharterTimes;
import com.example.smartcitymovie.ui.movie.MovieListActivity;
import com.example.smartcitymovie.ui.movie.MovieMessageActivity;
import com.example.smartcitymovie.ui.movie.PreviewMovieActivity;
import com.example.smartcitymovie.utils.OkHttpUtils;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class HomeFragment extends Fragment {

    private FragmentHomeBinding binding;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        HomeViewModel homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        setHasOptionsMenu(true);
        initView();
        return root;
    }

    private void initView() {
        loadBanner();
        loadWeather();
        loadFunction();
        loadHotMovieList();
        loadPriviewMovie();
        loadAreaMovieTHreater();
    }

    private void loadAreaMovieTHreater() {

        binding.RVAreaThreater.setLinearLayoutManager(LinearLayout.VERTICAL);
        binding.RVAreaThreater.setAdapter(ApiData.getAreaThreaterBean().getRows(), R.layout.area_threater_list_item_layout);
        binding.RVAreaThreater.getBaseAdapter().setOnRecycleViewItemCLickListener(new RecycleViewAdapter.OnRecycleViewItemCLickListener() {
            @Override
            public void onRecycleViewItemCLickListener(View view, int position) {
                Intent intent = new Intent(getActivity(), ChooseTharterTimes.class);
                intent.putExtra("tharterId", ApiData.getAreaThreaterBean().getRows().get(position).getId());
                startActivity(intent);
            }
        });

    }

    private void loadPriviewMovie() {
        //binding.RVPreviewMovie.setStaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL);
        //binding.RVPreviewMovie.setAdapter(getActivity(),"/prod-api/api/movie/film/preview/list", PreviewMovieListBean.class,R.layout.preview_movie_list_item_layout);
        PreviewMovieListBean previewMovieListBean = ApiData.getPreviewMovieListBean();
        requireActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                binding.RVPreviewMovie.setStaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL);
                binding.RVPreviewMovie.setAdapter(previewMovieListBean.getRows(), R.layout.preview_movie_list_item_layout);
            }
        });
    }

    /*
     * 加载热播影片
     * */
    private void loadHotMovieList() {
        binding.RVMovieHot.setStaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL);
        binding.RVMovieHot.setAdapter(ApiData.getMovieListBean().getRows(), R.layout.movie_list_item_layout);
        binding.RVMovieHot.getBaseAdapter().setOnPartRecycleViewItemClickListener(new RecycleViewAdapter.OnPartRecycleViewItemClickListener() {
            @Override
            public void onPartRecycleViewItemClickListener(View view, int position) {
                Intent intent = new Intent(getActivity(), MovieMessageActivity.class);
                intent.putExtra("id", ApiData.getMovieListBean().getRows().get(position).getId());
                startActivity(intent);
            }
        }, R.id.btn_buyTicket);
    }

    /*
     * 加载快捷应用
     * */
    private void loadFunction() {
        FunctionListBean functionListBean = new FunctionListBean();
        List<String> list = Arrays.asList(new String[]{"推荐", "预告", "影评", "星闻"});
        List<Integer> iconList = Arrays.asList(new Integer[]{R.drawable.movie_recommand, R.drawable.movie_notice, R.drawable.movie_comment, R.drawable.ic_baseline_fiber_news_24});
        List<FunctionListBean.RowsBean> rowsBeans = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            FunctionListBean.RowsBean rowsBean = new FunctionListBean.RowsBean();
            rowsBean.setIcon(iconList.get(i));
            rowsBean.setName(list.get(i));
            rowsBeans.add(rowsBean);
        }
        functionListBean.setRows(rowsBeans);
        binding.RVFunction.setGridLayoutManager(5);
        binding.RVFunction.setAdapter(functionListBean.getRows(), R.layout.function_list_item_layout);
        binding.RVFunction.getBaseAdapter().setOnRecycleViewItemCLickListener(new RecycleViewAdapter.OnRecycleViewItemCLickListener() {
            @Override
            public void onRecycleViewItemCLickListener(View view, int position) {
                switch (position) {
                    case 0:
                        startActivity(new Intent(getActivity(), MovieListActivity.class));
                        break;
                    case 1:
                        Toast.makeText(getActivity(),list.get(1),Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        Toast.makeText(getActivity(),list.get(2),Toast.LENGTH_SHORT).show();

                        break;
                    case 4:
                        Toast.makeText(getActivity(),list.get(3),Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }


    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        getActivity().getMenuInflater().inflate(R.menu.adress_menu, menu);
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (menu.findItem(R.id.address_menu) != null) {
                    menu.findItem(R.id.address_menu).setTitle(ApiData.getLocalAddressBean().getData().getCity());
                }
            }
        });
//        OkHttpUtils.getCall("/prod-api/api/common/gps/location").enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                LocalAddressBean localAddressBean = MyApplication.getGson().fromJson(response.body().string(), LocalAddressBean.class);
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (menu.findItem(R.id.address_menu) != null) {
//                            menu.findItem(R.id.address_menu).setTitle(localAddressBean.getData().getCity());
//                        }
//                    }
//                });
//
//            }
//        });
    }

    /*
     * 加载天气信息
     * */
    private void loadWeather() {
        binding.WVShowWeather.getSettings().setJavaScriptEnabled(true);
        binding.WVShowWeather.loadUrl("file:///android_asset/web/index.html");
        binding.WVShowWeather.setWebViewClient(new MyWebViewClient());
    }

    class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            TodayWeatherBean todayWeatherBean = ApiData.getTodayWeatherBean();
            String weatherMessage = "温度：" + todayWeatherBean.getData().getTemperature() + "，湿度：" + todayWeatherBean.getData().getHumidity() + "，空气质量：" + todayWeatherBean.getData().getAir();
            binding.WVShowWeather.loadUrl("javascript:setContent('" + todayWeatherBean.getData().getWeather() + "','" + weatherMessage + "')");

        }
    }

    private void loadBanner() {
        binding.HomeBanner.setAdapter(new BannerImageAdapter<MovieBannerBean.RowsBean>(ApiData.getMovieBannerBean().getRows()) {

                    @Override
                    public void onBindView(BannerImageHolder bannerImageHolder, MovieBannerBean.RowsBean rowsBean, int i, int i1) {
                        Glide.with(bannerImageHolder.imageView).load(rowsBean.getAdvImg()).into(bannerImageHolder.imageView);
                    }
                })
                .setBannerGalleryEffect(10, 10, 10)
                .setIndicator(new CircleIndicator(getActivity()))
                .start();
    }


}